import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
import '../utils/responsive_layout.dart';

/**
 * 现代化卡片组件
 * 提供统一的卡片样式和交互效果
 */
class ModernCard extends StatefulWidget {
  final Widget child;
  final EdgeInsetsGeometry? padding;
  final EdgeInsetsGeometry? margin;
  final Color? backgroundColor;
  final Color? borderColor;
  final double? borderRadius;
  final double? elevation;
  final VoidCallback? onTap;
  final VoidCallback? onLongPress;
  final bool isSelected;
  final bool isHoverable;
  final bool isClickable;
  final String? tooltip;
  final Widget? leading;
  final Widget? trailing;
  final CrossAxisAlignment? crossAxisAlignment;
  final MainAxisAlignment? mainAxisAlignment;

  const ModernCard({
    Key? key,
    required this.child,
    this.padding,
    this.margin,
    this.backgroundColor,
    this.borderColor,
    this.borderRadius,
    this.elevation,
    this.onTap,
    this.onLongPress,
    this.isSelected = false,
    this.isHoverable = true,
    this.isClickable = true,
    this.tooltip,
    this.leading,
    this.trailing,
    this.crossAxisAlignment,
    this.mainAxisAlignment,
  }) : super(key: key);

  @override
  State<ModernCard> createState() => _ModernCardState();
}

class _ModernCardState extends State<ModernCard>
    with SingleTickerProviderStateMixin {
  bool _isHovered = false;
  bool _isPressed = false;
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  late Animation<double> _elevationAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 150),
      vsync: this,
    );
    
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 0.98,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
    
    _elevationAnimation = Tween<double>(
      begin: 0.0,
      end: 4.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  void _handleHoverChange(bool isHovered) {
    if (!widget.isHoverable) return;
    
    setState(() {
      _isHovered = isHovered;
    });
    
    if (isHovered) {
      _animationController.forward();
    } else {
      _animationController.reverse();
    }
  }

  void _handleTapDown(TapDownDetails details) {
    if (!widget.isClickable) return;
    
    setState(() {
      _isPressed = true;
    });
  }

  void _handleTapUp(TapUpDetails details) {
    if (!widget.isClickable) return;
    
    setState(() {
      _isPressed = false;
    });
  }

  void _handleTapCancel() {
    if (!widget.isClickable) return;
    
    setState(() {
      _isPressed = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    
    // 响应式配置
    final responsivePadding = widget.padding ?? 
        ResponsiveLayoutConfig.cardMargin.getValue(context);
    final responsiveMargin = widget.margin ?? 
        const EdgeInsets.symmetric(horizontal: 4, vertical: 2);
    
    // 计算背景色
    Color backgroundColor = widget.backgroundColor ?? colorScheme.surface;
    if (widget.isSelected) {
      backgroundColor = colorScheme.primaryContainer;
    } else if (_isHovered && widget.isHoverable) {
      backgroundColor = colorScheme.surfaceVariant.withOpacity(0.5);
    }
    
    // 计算边框色
    Color borderColor = widget.borderColor ?? colorScheme.outline.withOpacity(0.2);
    if (widget.isSelected) {
      borderColor = colorScheme.primary;
    } else if (_isHovered && widget.isHoverable) {
      borderColor = colorScheme.outline.withOpacity(0.4);
    }
    
    Widget cardContent = widget.child;
    
    // 如果有leading或trailing，使用Row布局
    if (widget.leading != null || widget.trailing != null) {
      cardContent = Row(
        crossAxisAlignment: widget.crossAxisAlignment ?? CrossAxisAlignment.center,
        mainAxisAlignment: widget.mainAxisAlignment ?? MainAxisAlignment.start,
        children: [
          if (widget.leading != null) ...[
            widget.leading!,
            SizedBox(width: ResponsiveSpacing.small.getValue(context)),
          ],
          Expanded(child: widget.child),
          if (widget.trailing != null) ...[
            SizedBox(width: ResponsiveSpacing.small.getValue(context)),
            widget.trailing!,
          ],
        ],
      );
    }
    
    Widget card = AnimatedBuilder(
      animation: _animationController,
      builder: (context, child) {
        return Transform.scale(
          scale: _isPressed ? 0.95 : _scaleAnimation.value,
          child: Container(
            margin: responsiveMargin,
            decoration: BoxDecoration(
              color: backgroundColor,
              borderRadius: BorderRadius.circular(widget.borderRadius ?? 8),
              border: Border.all(
                color: borderColor,
                width: widget.isSelected ? 2 : 1,
              ),
              boxShadow: widget.elevation != null || _isHovered
                  ? [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.1),
                        blurRadius: widget.elevation ?? _elevationAnimation.value,
                        offset: Offset(0, (widget.elevation ?? _elevationAnimation.value) / 2),
                      ),
                    ]
                  : null,
            ),
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: widget.onTap,
                onLongPress: widget.onLongPress,
                onTapDown: _handleTapDown,
                onTapUp: _handleTapUp,
                onTapCancel: _handleTapCancel,
                onHover: _handleHoverChange,
                borderRadius: BorderRadius.circular(widget.borderRadius ?? 8),
                child: Padding(
                  padding: responsivePadding,
                  child: cardContent,
                ),
              ),
            ),
          ),
        );
      },
    );
    
    // 如果有tooltip，包装Tooltip组件
    if (widget.tooltip != null) {
      card = Tooltip(
        message: widget.tooltip!,
        child: card,
      );
    }
    
    return card;
  }
}

/**
 * 现代化列表卡片
 * 专门用于列表项的卡片组件
 */
class ModernListCard extends StatelessWidget {
  final Widget? leading;
  final Widget title;
  final Widget? subtitle;
  final Widget? trailing;
  final VoidCallback? onTap;
  final VoidCallback? onLongPress;
  final bool isSelected;
  final bool isThreeLine;
  final EdgeInsetsGeometry? contentPadding;

  const ModernListCard({
    Key? key,
    this.leading,
    required this.title,
    this.subtitle,
    this.trailing,
    this.onTap,
    this.onLongPress,
    this.isSelected = false,
    this.isThreeLine = false,
    this.contentPadding,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    
    return ModernCard(
      onTap: onTap,
      onLongPress: onLongPress,
      isSelected: isSelected,
      padding: contentPadding ?? const EdgeInsets.symmetric(
        horizontal: 16,
        vertical: 12,
      ),
      child: Row(
        children: [
          if (leading != null) ...[
            leading!,
            const SizedBox(width: 16),
          ],
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                DefaultTextStyle(
                  style: theme.textTheme.bodyLarge!,
                  child: title,
                ),
                if (subtitle != null) ...[
                  const SizedBox(height: 4),
                  DefaultTextStyle(
                    style: theme.textTheme.bodyMedium!.copyWith(
                      color: theme.colorScheme.onSurfaceVariant,
                    ),
                    child: subtitle!,
                  ),
                ],
              ],
            ),
          ),
          if (trailing != null) ...[
            const SizedBox(width: 16),
            trailing!,
          ],
        ],
      ),
    );
  }
}

/**
 * 现代化操作卡片
 * 带有操作按钮的卡片组件
 */
class ModernActionCard extends StatelessWidget {
  final Widget child;
  final List<Widget> actions;
  final EdgeInsetsGeometry? padding;
  final EdgeInsetsGeometry? margin;
  final bool showDivider;

  const ModernActionCard({
    Key? key,
    required this.child,
    this.actions = const [],
    this.padding,
    this.margin,
    this.showDivider = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    
    return ModernCard(
      padding: EdgeInsets.zero,
      margin: margin,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisSize: MainAxisSize.min,
        children: [
          Padding(
            padding: padding ?? const EdgeInsets.all(16),
            child: child,
          ),
          if (actions.isNotEmpty) ...[
            if (showDivider)
              Divider(
                height: 1,
                thickness: 1,
                color: theme.colorScheme.outline.withOpacity(0.2),
              ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: actions
                    .map((action) => Padding(
                          padding: const EdgeInsets.only(left: 8),
                          child: action,
                        ))
                    .toList(),
              ),
            ),
          ],
        ],
      ),
    );
  }
}

/**
 * 现代化信息卡片
 * 用于显示信息的卡片组件
 */
class ModernInfoCard extends StatelessWidget {
  final IconData? icon;
  final String title;
  final String? subtitle;
  final String? description;
  final Color? iconColor;
  final VoidCallback? onTap;
  final Widget? trailing;

  const ModernInfoCard({
    Key? key,
    this.icon,
    required this.title,
    this.subtitle,
    this.description,
    this.iconColor,
    this.onTap,
    this.trailing,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    
    return ModernCard(
      onTap: onTap,
      child: Row(
        children: [
          if (icon != null) ...[
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: (iconColor ?? colorScheme.primary).withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Icon(
                icon,
                color: iconColor ?? colorScheme.primary,
                size: 24,
              ),
            ),
            const SizedBox(width: 16),
          ],
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  title,
                  style: theme.textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.w600,
                  ),
                ),
                if (subtitle != null) ...[
                  const SizedBox(height: 2),
                  Text(
                    subtitle!,
                    style: theme.textTheme.bodyMedium?.copyWith(
                      color: colorScheme.primary,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
                if (description != null) ...[
                  const SizedBox(height: 4),
                  Text(
                    description!,
                    style: theme.textTheme.bodySmall?.copyWith(
                      color: colorScheme.onSurfaceVariant,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ],
            ),
          ),
          if (trailing != null) ...[
            const SizedBox(width: 16),
            trailing!,
          ],
        ],
      ),
    );
  }
}